import { reactive, ref, watchEffect } from "vue";

export const useList = <T>(
  query: H5App.DataPagingQuery,
  fn: (query: H5App.DataPagingQuery) => Promise<{ list: T[]; size: number }>
) => {
  const listData = ref<T[]>([]);
  const listLoading = ref(false);
  const listFinish = ref(false);
  const reloadList = () => {
    query.page = 1;
    return fn(query)
      .then((resp) => renderList(resp.list, resp.size))
      .catch(() => {
        listFinish.value = true;
        listLoading.value = false;
      });
  };
  const renderList = (items: any[], size: number) => {
    query.page === 1 ? (listData.value = items) : listData.value.push(...items);
    listFinish.value = size !== items.length;
    listLoading.value = false;
  };
  const loadMoreList = () => {
    if (listLoading.value) return Promise.resolve();
    listLoading.value = true;
    query.page += 1;
    return fn(query)
      .then((resp) => renderList(resp.list, resp.size))
      .catch(() => {
        listFinish.value = true;
        listLoading.value = false;
      });
  };
  return { listData, listLoading, listFinish, reloadList, loadMoreList };
};

export const useTabs = (tabs: string[]) => {
  const tabsRef = ref();
  const tabsData = reactive({ index: 0, list: tabs, cacheList: [0] });
  watchEffect(() => {
    tabsData.cacheList.includes(tabsData.index) ||
      tabsData.cacheList.push(tabsData.index);
  });
  const tabsClick = () => {
    (tabsRef.value as any)?.swipeTo(tabsData.index);
  };
  const tabsChange = (index: number) => {
    tabsData.index = index;
  };
  return { tabsRef, tabsData, tabsClick, tabsChange };
};
